﻿using Android.Content.Res;
using Android.Media;
using Games.Droid;
using Xamarin.Forms;

[assembly: Dependency(typeof(MediaHandler))]
namespace Games.Droid
{
    class MediaHandler : IMediaHandler
    {
        private MediaPlayer player;
        private string fileName = "music.wav";
        private AssetFileDescriptor music;

        public MediaHandler()
        {
            this.music = Android.App.Application.Context.Assets.OpenFd(fileName);
        }
        public void Play()
        {
            this.player = new MediaPlayer();
            this.player.SetVolume(100, 100);
            this.player.Prepared += (s, e) =>
            {
                this.player.Start();
            };
            this.player.SetDataSource(music.FileDescriptor, music.StartOffset, music.Length);
            this.player.Looping = true;
            this.player.Prepare();
        }

        public void SetVolume(int vol)
        {
            if(this.player != null)
            {
                if(vol > 100)
                    vol = 100;
                if(vol < 0)
                    vol = 0;
                this.player.SetVolume(vol, vol);
            }
        }

        public void Pause()
        {
            if(this.player != null && this.player.IsPlaying)
            {
                this.player.Pause();
            }
        }

        public void Resume()
        {
            if(this.player != null && !this.player.IsPlaying)
            {
                this.player.Start();
            }
        }

        public void Stop()
        {
            this.player.Stop();
            this.player.Release();
            this.player = null;
        }
    }
    //class SoundHandler
    //{
    //    private SoundPool soundPool = new SoundPool(4, Stream.Music, 100);
    //    private Dictionary<string, int> soundPoolMap = new Dictionary<string, int>();

    //    public SoundHandler()
    //    {
    //        soundPoolMap.Add("1", soundPool.Load(Android.App.Application.Context.Assets.OpenFd(""), 1));
    //    }

    //    public void PlaySound(string sound, int loopTimes)
    //    {
    //        AudioManager mgr = (AudioManager)Android.App.Application.Context.GetSystemService(Android.Content.Context.AudioService);
    //        float streamVolumeCurrent = mgr.GetStreamVolume(Stream.Music);
    //        float streamVolumeMax = mgr.GetStreamMaxVolume(Stream.Music);
    //        float volume = streamVolumeCurrent / streamVolumeMax;

    //        soundPool.Play(soundPoolMap[sound], volume, volume, 1, loop, 1f);
    //    }
    //}
}


